const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let id = req.body.id;
	let name = req.body.name;
	let price = req.body.price;
	let introduce = req.body.introduce;
	let imgurl = req.body.imgurl;
	let able = req.body.able;

	if (id == undefined) {
		sendResponse('error','no selected id', null, res);
		return;
	}

	let editSql = '';
	let params = [];

	if (name != undefined) {
		editSql += 'name = ?, ';
		params.push(name);
	}

	if (price != undefined) {
		editSql += 'price = ?, ';
		params.push(price);
	}

	if (introduce != undefined) {
		editSql += 'introduce = ?, ';
		params.push(introduce);
	}
	
	if (imgurl != undefined) {
		editSql += 'imgurl = ?, ';
		params.push(imgurl);
	}

	if (able != undefined) {
		editSql += 'able = ?, ';
		params.push(able);
	}

	if (producetime != undefined) {
		editSql += 'producetime = ?, ';
		params.push(producetime);
	}
	
	if (abletime != undefined) {
		editSql += 'abletime = ?, ';
		params.push(abletime);
	}

	if (code != undefined) {
		editSql += 'code = ?, ';
		params.push(code);
	}

	if (company != undefined) {
		editSql += 'company = ?, ';
		params.push(company);
	}

	if (address != undefined) {
		editSql += 'address = ?, ';
		params.push(address);
	}
	
	if (phone != undefined) {
		editSql += 'phone = ?, ';
		params.push(phone);
	}

	params.push(id);

	if (editSql == '') {
		sendResponse('error','no change content', null, res);
		return;
	} else {
		editSql = editSql.slice(0, -2);
	}


	let sql = 'UPDATE medicine SET ' + editSql + ' WHERE id = ?';

	pool.getConnection(function(err, connection) {
		if (err) { 
			sendResponse('error','database error', null, res);
			return;
		}
		connection.query(sql, params, function (error, rows, fields) {

			connection.release();

			if (error) { 
				if (error.code = "ER_DUP_ENTRY") {
					sendResponse('error','ER_DUP_ENTRY', null, res);
					return;
				} else {
					sendResponse('error','database error', null, res);
					return;
				}
			} else {
				sendResponse('ok','edit success', null, res);
				return;
			}

		})	

	});

}